# -*- coding: utf-8 -*-
from utils.views import WdListCreateAPIView, WdRetrieveUpdateAPIView, WdDestroyAPIView, WdListAPIView, WdAPIView, AuthenticationExceptView
from models import Contract, Task
from serializer import MaintainSerializer, MaintainListSerializer, TaskSerializer, TaskListSerializer, \
    MaintainHistoryListSerializer, MaintainHistoryDetailSerializer, TaskHistoryListSerializer, TaskResultSerializer
# from users.models import CompanyInfo
from basic.models import ElevatorInfo, ElevatorPersonInfo, ElevatorFollowedByUser
from users.models import CompanyInfo, CompanyPerson
# from utils.response import ErrorCode
import datetime
import json
import operator
from rest_framework import status
from utils.response import general_json_response, ErrorCode
from django.db.models import Q
from rest_framework.response import Response
from ElevatorAdmin.tasks import submit, manual_submission, data_sync
from utils.logger import get_logger
from django.shortcuts import render
from ElevatorAdmin.settings import DOMAIN_NAME, TO_GOV
import pdfkit
from django.db.models.signals import post_save, post_delete


logger = get_logger(__name__)


def task_data_sync(sender, **kwargs):
    if not TO_GOV:
        return
    obj = kwargs['instance']
    data_sync.delay(obj.id)
    print '捕捉到save信号，数据开始同步'


class MaintainListCreateView(WdListCreateAPIView, WdDestroyAPIView):
    model = Contract
    p_serializer_class = MaintainSerializer
    g_serializer_class = MaintainListSerializer
    # POST_CHECK_REQUEST_PARAMETER = ('contract_no', 'contract_type', 'maintain_company', 'property_company',
    #                                 'start_time', 'end_time', 'contract_name', 'maintain_cycle',
    #                                 'contract_file')
    SEARCH_FIELDS = ('contract_name', 'contract_no', )
    FOREIGN_SEARCH_FIELD_MAP = {'property_company': [CompanyInfo, 'name'], 'maintain_company': [CompanyInfo, 'name']}
    FILTER_FIELDS = ('registry_status', )
    # DELETE_CHECK_REQUEST_PARAMETER = ('contract_ids',)

    def get_serializer_class(self, *args, **kwargs):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "post":
            return self.p_serializer_class

    def qs_search(self, qs):
        key_words = self.request.GET.get(self.SEARCH_KEY, None)
        if key_words is None or not key_words:
            return qs
        if len(key_words) == 20:
            try:
                elevator_obj = ElevatorInfo.objects.filter_active(register_code=key_words).first()
                contract_id = elevator_obj.contract.id
                qs = qs.filter(id=contract_id)
                return qs
            except Exception as e:
                pass
        search_sql = []
        for search_field in self.SEARCH_FIELDS:
            search_sql.append(Q(**{"%s__icontains" % search_field: key_words}))
        search_sql += self.process_foreign_search()
        if len(search_sql) == 0:
            return qs
        else:
            query = reduce(operator.or_, search_sql)
            qs = qs.filter(query)
        return qs

    def qs_filter(self, qs):
        today = datetime.datetime.combine(datetime.date.today(), datetime.time())
        qs = super(MaintainListCreateView, self).qs_filter(qs)
        user = self.request.user
        if user.role == 30:
            com = CompanyPerson.objects.filter_active(auth_user=user).first().company
            qs = qs.filter(property_company=com)
        ids = []
        expire = self.request.GET.get('expire', None)
        if not expire:
            return qs
        if expire == u'red':
            for c in qs:
                end_time = datetime.datetime.strptime(c.end_time, "%Y-%m-%d") if u"-" in c.end_time else datetime.datetime.strptime(c.end_time, "%Y/%m/%d")
                if end_time < today:
                    ids.append(c.id)
        elif expire == u'yellow':
            for c in qs:
                end_time = datetime.datetime.strptime(c.end_time, "%Y-%m-%d") if u"-" in c.end_time else datetime.datetime.strptime(c.end_time, "%Y/%m/%d")
                if end_time >= today and (end_time - today).days < 90:
                    ids.append(c.id)
        elif expire == u'green':
            for c in qs:
                end_time = datetime.datetime.strptime(c.end_time, "%Y-%m-%d") if u"-" in c.end_time else datetime.datetime.strptime(c.end_time, "%Y/%m/%d")
                if end_time >= today and (end_time - today).days >= 90:
                    ids.append(c.id)
        else:
            return qs
        qs = qs.filter(id__in=ids)
        return qs

    def delete(self, request, *args, **kwargs):
        contract_ids = self.request.data.get('contract_ids', [])
        Contract.objects.filter_active(id__in=contract_ids).update(is_active=False)
        for contract_id in contract_ids:
            elevator_qs = ElevatorInfo.objects.filter_active(contract=contract_id)
            for elevator_obj in elevator_qs:
                elevator_obj.contract = None
                elevator_obj.save()
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)

    # def qs_business_role(self, qs):
    #     user = self.request.user
    #     if user.role == 0:
    #         return qs
    #     qs = qs.filter(maintain_company=user.company_info)
    #     return qs

    def perform_create(self, serializer):
        super(MaintainListCreateView, self).perform_create(serializer)
        elevator_ids = self.request.data.get('elevator_info')
        contract_id = serializer.data['id']
        contract_obj = self.model.objects.get(id=contract_id)
        for elevator_id in elevator_ids:
            elevator_obj = ElevatorInfo.objects.get(id=elevator_id)
            elevator_obj.contract = contract_obj
            elevator_obj.save()

    def post_check_parameter(self, kwargs):
        code = super(MaintainListCreateView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        contract_file = self.request.data.pop('contract_file', None)
        contract_file = json.dumps(contract_file)
        self.request.data['contract_file'] = contract_file
        # maintain_company_id = self.request.data.get('maintain_company', None)
        # self.request.data.update({'service_id': maintain_company_id})
        return code

    # def post_check_parameter(self, kwargs):
    #     code = super(MaintainListCreateView, self).post_check_parameter(kwargs)
    #     if code != ErrorCode.SUCCESS:
    #         return code
    #     property_company = CompanyInfo.objects.get(id=self.property_company_id)
    #     maintain_company = CompanyInfo.objects.get(id=self.maintain_company_id)
    #     self.request.data.update({
    #         "property_company_name": property_company.name,
    #         "maintain_company_name": maintain_company.name,
    #     })
    #     return code

    # def qs_search(self, qs):
    #     name = self.request.GET.get('name', None)
    #
    #     if name:
    #         qs = qs.filter(name__icontains=name)
    #     elevator_name = self.request.GET.get('elevator', None)
    #
    #     if elevator_name:
    #         qs = qs.filter(elevator_name__icontains=elevator_name)
    #     return qs


class MaintainDetailView(WdRetrieveUpdateAPIView, WdDestroyAPIView):
    model = Contract
    p_serializer_class = MaintainSerializer
    g_serializer_class = MaintainListSerializer
    POST_DATA_RESPONSE = True
    # POST_CHECK_REQUEST_PARAMETER = ('contract_no', 'contract_type', 'maintain_company', 'property_company',
    #                                 'start_time', 'end_time', 'contract_name', 'maintain_cycle')

    def get_serializer_class(self, *args, **kwargs):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "put":
            return self.p_serializer_class

    def post_check_parameter(self, kwargs):
        code = super(MaintainDetailView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        # 修改电梯绑定
        new_elevator_ids = self.request.data.get('elevator_info')
        contract_id = self.get_id()
        elevator_qs = ElevatorInfo.objects.filter(contract_id=contract_id)
        if elevator_qs:
            elevator_qs.update(contract=None)
        if new_elevator_ids:
            new_elevator_qs = ElevatorInfo.objects.filter_active(id__in=new_elevator_ids)
            if new_elevator_qs:
                new_elevator_qs.update(contract_id=contract_id)
        #
        # old_elevator_ids = list()
        # for elevator in elevator_qs:
        #     old_elevator_ids.append(elevator.id)
        # for old_elevator_id in old_elevator_ids:
        #     if old_elevator_id not in new_elevator_ids:
        #         old_elevator_obj = ElevatorInfo.objects.get(id=old_elevator_id)
        #         old_elevator_obj.contract = None
        #         old_elevator_obj.save()
        #     else:
        #         new_elevator_ids.remove(old_elevator_id)
        # for new_elevator_id in new_elevator_ids:
        #     new_elevator_obj = ElevatorInfo.objects.get(id=new_elevator_id)
        #     new_elevator_obj.contract = self.get_object()
        #     new_elevator_obj.save()
        contract_file = self.request.data.pop('contract_file', None)
        contract_file = json.dumps(contract_file)
        self.request.data['contract_file'] = contract_file
        # maintain_company_id = self.request.data.get('maintain_company', None)
        # self.request.data.update({'service_id': maintain_company_id})
        return code

    # 删除合同的同时，将电梯与合同解除绑定
    def perform_destroy(self, instance):
        if self.OBJECT_WITH_ACTIVE:
            contract_id = self.get_object().id
            elevator_qs = ElevatorInfo.objects.filter(contract=contract_id)
            for elevator in elevator_qs:
                elevator.contract = None
                elevator.save()
            instance.is_active = False
            if hasattr(instance, 'last_modify_user_id'):
                instance.last_modify_user_id = self.request.user.id
            instance.save()
        else:
            instance.delete()


class TaskView(WdListCreateAPIView, WdDestroyAPIView):
    model = Task
    serializer_class = TaskSerializer
    g_serializer_class = TaskListSerializer
    # POST_DATA_ID_RESPONSE = True
    # POST_DATA_RESPONSE = True
    SEARCH_FIELDS = ("sn", )
    FILTER_FIELDS = ('status',)
    FOREIGN_SEARCH_FIELD_MAP = {'elevator': [ElevatorInfo, 'register_code']}
    FOREIGN_SEARCH_FIELD_MAP_1 = {'elevator': [ElevatorInfo, 'property_company_name']}

    def qs_filter_by_ele(self, qs):
        user = self.request.user
        if user.role == 0:
            return qs
        if user.role == 20 and user.company_person.is_admin:
            return qs
        if user.role == 30 and user.company_person.is_admin:
            cp = CompanyPerson.objects.filter_active(auth_user=user, is_admin=True).first()
            com = cp.company
            es = ElevatorInfo.objects.filter_active(property_company=com).values_list("id", flat=True).distinct()
            qs = qs.filter(elevator_id__in=es)
            return qs
        if user.role == 40 and user.company_person.is_admin:
            rg = ElevatorInfo.objects.filter_active(supervised=1).values_list("register_code", flat=True).distinct()
            qs = qs.filter(elevator__register_code__in=rg)
            return qs
        codes = self.get_registers()
        qs = qs.filter(elevator__register_code__in=codes)
        return qs

    def process_foreign_search(self):
        key_words = self.request.GET.get(self.SEARCH_KEY, None)
        search_sql = []
        for key_name in self.FOREIGN_SEARCH_FIELD_MAP:
            search_info = self.FOREIGN_SEARCH_FIELD_MAP[key_name]
            foreign_cls = search_info[0]
            foreign_field = search_info[1]
            ids = foreign_cls.objects.filter(**{"%s__icontains" % foreign_field: key_words})
            search_sql.append(Q(**{"%s__in" % key_name: ids}))
        for key_name in self.FOREIGN_SEARCH_FIELD_MAP_1:
            search_info = self.FOREIGN_SEARCH_FIELD_MAP_1[key_name]
            foreign_cls = search_info[0]
            foreign_field = search_info[1]
            ids = foreign_cls.objects.filter(**{"%s__icontains" % foreign_field: key_words})
            search_sql.append(Q(**{"%s__in" % key_name: ids}))
        return search_sql

    def qs_filter(self, qs):
        # qs = super(TaskView, self).qs_filter(qs)
        t = self.request.GET.get("today", None)
        now = datetime.date.today()
        today = datetime.datetime(year=now.year, month=now.month, day=now.day)
        if t:
            qs = qs.filter(day=now)
        yesterday = today - datetime.timedelta(days=1)
        task_status = self.request.GET.get("status", None)
        alarm = self.request.GET.get("alarm", None)
        if self.request.user.role == 0 and task_status:
            qs = qs.filter(status=task_status)
        print "alarm: %s" % alarm
        if self.request.user.role == 0 and alarm:
            if alarm == u"1":
                qs = qs.filter(status__in=(50, 60, 70, 90, 110, 120, 130, 140), task_end_time__gte=today)
            elif alarm == u"2":
                qs = qs.filter(status__in=(50, 60, 70, 90, 110, 120, 130, 140), task_end_time__gte=yesterday,
                               task_end_time__lt=today)
            else:
                qs = qs.filter(status__in=(50, 60, 70, 90, 110, 120, 130, 140), task_end_time__lt=yesterday)

        elif self.request.user.role in (20, 40) and task_status:
            if int(task_status) == 30:
                s = (30, 60, 70, 80, 90, 110, 120, 130, 140)
                qs = qs.filter(status__in=s)
            elif int(task_status) == 20:
                qs = qs.filter(status=20)
            elif int(task_status) == 50:
                qs = qs.filter(status=50)
            elif int(task_status) == 100:
                qs = qs.filter(status=100)
            else:
                qs = qs.filter(status=task_status)
        time_from = self.request.GET.get("time_from", None)
        time_to = self.request.GET.get("time_to", None)
        if time_from and not time_to:
            qs = qs.filter(day__gte=time_from)
        if time_from and time_to:
            qs = qs.filter(day__gte=time_from, day__lte=time_to)

        three_days_later = today + datetime.timedelta(days=3)
        time_status = self.request.GET.get("time_status", None)
        if time_status == u"10":
            qs = qs.filter(day__lt=today, status=10)
        elif time_status == u"20":
            qs = qs.filter(day__lte=three_days_later, day__gte=today, status=10)
        elif time_status == u"30":
            qs = qs.exclude(status=10, day__lte=three_days_later)
        elif time_status == u"40":
            qs = qs.filter(result__isnull=True)
        elif time_status == u"50":
            qs = qs.filter(Q(result__icontains=u"非正常") | Q(result__icontains=u"无此项"))
        follow = self.request.GET.get("follow", None)
        if follow == u"1":
            eis = ElevatorFollowedByUser.objects.filter_active(user=self.request.user).values_list("elevator", flat=True).distinct()
            qs = qs.filter(elevator__in=eis)
        return qs

    def qs_search(self, qs):
        key_words = self.request.GET.get(self.SEARCH_KEY, None)
        if key_words is None or not key_words:
            return qs
        search_sql = []
        for search_field in self.SEARCH_FIELDS:
            search_sql.append(Q(**{"%s__icontains" % search_field: key_words}))
        search_sql += self.process_foreign_search()
        if len(search_sql) == 0:
            return qs
        else:
            query = reduce(operator.or_, search_sql)
            qs = qs.filter(query)
        return qs

    # def qs_order_by(self, qs):
    #     order_by = self.get_order_by_name()
    #     if order_by == 'internal_no':
    #         qs = qs.order_by('elevator__internal_no')
    #     if order_by == '-internal_no':
    #         qs = qs.order_by('-elevator__internal_no')
    #     if order_by == 'register_code':
    #         qs = qs.order_by('elevator__register_code')
    #     if order_by == '-register_code':
    #         qs = qs.order_by('-elevator__register_code')
    #     else:
    #         qs = qs.order_by(order_by)
    #     return qs

    def create(self, request, *args, **kwargs):
        elevator_info = self.request.data.pop('elevator_info')
        day = self.request.data.pop('day', None)
        if day:
            year, month, day = day.split("-")
            day = datetime.date(int(year), int(month), int(day))
            self.request.data.update({'day': day})
        for item in elevator_info:
            elevator_id = item[0]
            worker = json.dumps(item[1])
            maintain_type = item[2]
            pre_obj = Task.objects.order_by('-id').first()
            today = datetime.datetime.now().strftime("%Y-%m-%d")
            today = "".join(today.split("-")).decode()
            s_t = u"BYGD" + today
            if pre_obj and pre_obj.sn.startswith(s_t):
                pre_tail = pre_obj.sn.split(s_t)[1]
                pre_tail = int(pre_tail)
                tail = pre_tail + 1
                tail = unicode(tail).rjust(6, u'0')
                sn = s_t + tail
            else:
                sn = s_t + u'000001'
            self.request.data.update({'elevator': elevator_id})
            self.request.data.update({"worker": worker})
            self.request.data.update({"maintain_type": maintain_type})
            self.request.data.update({'sn': sn})
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            del self.request.data['elevator']
            del self.request.data['worker']
            del self.request.data['maintain_type']
            del self.request.data['sn']
        return Response(status=status.HTTP_201_CREATED)

    def delete(self, request, *args, **kwargs):
        task_ids = self.request.data.get('task_ids', [])
        Task.objects.filter_active(id__in=task_ids).update(is_active=False)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class TaskDetailView(WdRetrieveUpdateAPIView, WdDestroyAPIView):
    model = Task
    p_serializer_class = TaskSerializer
    g_serializer_class = TaskListSerializer
    POST_DATA_RESPONSE = True

    def get_serializer_class(self, *args, **kwargs):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "put":
            return self.p_serializer_class

    def post_check_parameter(self, kwargs):
        code = super(TaskDetailView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        day = self.request.data.pop('day', None)
        if day:
            year, month, day = day.split("-")
            day = datetime.date(int(year), int(month), int(day))
            self.request.data.update({'day': day})
        # if self.request.data.has_key('task_end_time'):
        #     task_end_time = self.request.data.pop('task_end_time', None)
        #     if task_end_time:
        #         year, month, day = task_end_time.split("-")
        #         task_end_time = datetime.date(int(year), int(month), int(day))
        #         self.request.data.update({'task_end_time': task_end_time})
        elevator_info = self.request.data.pop('elevator_info')
        elevator_id = elevator_info[0]
        worker = elevator_info[1]
        worker = json.dumps(worker)
        maintain_type = elevator_info[2]
        self.request.data.update({'elevator': elevator_id})
        self.request.data.update({'worker': worker})
        self.request.data.update({'maintain_type': maintain_type})
        return code


# 维保历史接口
class MaintainHistoryListView(WdListCreateAPIView):
    model = ElevatorInfo
    g_serializer_class = MaintainHistoryListSerializer
    p_serializer_class = None
    POST_DATA_RESPONSE = True
    SEARCH_FIELDS = ('register_code', 'property_company_name', 'maintain_company_name')

    def get_serializer_class(self):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "post":
            return self.p_serializer_class

    # def qs_business_role(self, request, *args, **kwargs):
    #     user = self.request.user
    #     e_ids = []
    #     if user.role == 0:
    #         e_qs = ElevatorInfo.objects.filter_active(registry_status=20)
    #         for obj in e_qs:
    #             task_qs = Task.objects.filter_active(elevator=obj.id)
    #             if task_qs.count():
    #                 e_ids.append(obj.id)
    #         qs = ElevatorInfo.objects.filter_active(id__in=e_ids)
    #     elif user.role == 20:
    #         e_qs = ElevatorInfo.objects.filter_active(maintain_company=user.company_person.company.id,
    #                                                   registry_status=20)
    #         for obj in e_qs:
    #             task_qs = Task.objects.filter_active(elevator=obj.id)
    #             if task_qs.count():
    #                 e_ids.append(obj.id)
    #         qs = ElevatorInfo.objects.filter_active(id__in=e_ids)
    #     return qs

    def qs_filter(self, qs):
        qs = super(MaintainHistoryListView, self).qs_filter(qs)
        es = Task.objects.filter_active().values_list("elevator", flat=True).distinct()
        qs = qs.filter(id__in=es, registry_status=20)
        user = self.request.user
        if user.role == 30:
            com = CompanyPerson.objects.filter_active(auth_user=user).first().company
            qs = qs.filter(property_company=com)
        elif user.role == 40:
            qs = qs.filter(supervised=1)
        return qs

    def qs_filter_by_ele(self, qs):
        user = self.request.user
        if user.role == 0:
            return qs
        if user.role in [20, 30, 40] and user.company_person.is_admin:
            return qs
        codes = self.get_registers()
        qs = qs.filter(register_code__in=codes)
        return qs


class MaintainHistoryDetailView(WdRetrieveUpdateAPIView):
    model = ElevatorInfo
    g_serializer_class = MaintainHistoryDetailSerializer
    p_serializer_class = None
    POST_DATA_RESPONSE = True

    def get_serializer_class(self):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "put":
            return self.p_serializer_class


class TaskHistoryListView(WdListCreateAPIView):
    model = Task
    g_serializer_class = TaskHistoryListSerializer
    p_serializer_class = None
    POST_DATA_RESPONSE = True
    FOREIGN_SEARCH_FIELD_MAP = {'elevator': [ElevatorInfo, 'register_code']}

    def get_serializer_class(self):
        if self.request.method.lower() == "get":
            return self.g_serializer_class
        elif self.request.method.lower() == "post":
            return self.p_serializer_class

    def qs_search(self, qs):
        key_words = self.request.GET.get(self.SEARCH_KEY, None)
        if key_words is None or not key_words:
            return qs
        search_sql = []
        for search_field in self.SEARCH_FIELDS:
            search_sql.append(Q(**{"%s__icontains" % search_field: key_words}))
        search_sql += self.process_foreign_search()
        if len(search_sql) == 0:
            return qs
        else:
            query = reduce(operator.or_, search_sql)
            qs = qs.filter(query)
        return qs


# 工单编辑时，获取电梯绑定的维保人员
class GetElevatorPersonView(WdListAPIView):

    def get(self, request, *args, **kwargs):
        worker_info = []
        elevator_id = self.request.GET.get("elevator_id")
        ep_qs = ElevatorPersonInfo.objects.filter(elevator=elevator_id, worker_type=10)
        if ep_qs.count():
            for ep_obj in ep_qs:
                worker_dic = dict()
                worker_dic["person_id"] = ep_obj.worker.id
                worker_dic["person_name"] = ep_obj.worker.auth_user.real_name
                worker_info.append(worker_dic)
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, worker_info)
        else:
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, worker_info)


class TaskNotDoneStatisticView(WdAPIView):

    def get(self, request, *args, **kwargs):
        user = self.request.user
        if user.role == 20:
            company = user.company_person.company
            time_delta = self.request.GET.get('time_delta', u'3')
            today = datetime.date.today()
            time_to = today + datetime.timedelta(days=int(time_delta))
            number = Task.objects.filter_active(day__gte=today, day__lte=time_to, status=10,
                                                elevator__maintain_company=company).count()
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, number)
        else:
            return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, None)


class TaskSubmitView(WdAPIView):

    def post(self, request, *args, **kwargs):
        task_ids = self.request.data.get('task_ids')
        if not task_ids:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT)
        tasks = Task.objects.filter_active(id__in=task_ids, status=50)
        if not tasks:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT, u"数据不可重复提交")
        logger.info(len(tasks))
        logger.info("submit msg by pc")
        for task in tasks:
            task.status = 60
            task.save()
            logger.info("task.id: %s " % task.id)
            b = True if task.estate_confirm else False
            submit.delay(task.id, b)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class TaskSubmitForWrongTaskView(WdAPIView):
    def post(self, request, *args, **kwargs):
        task_ids = self.request.data.get('task_ids')
        if not task_ids:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT)
        manual_submission.delay(task_ids)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class TaskResultRetrieveAndUpdateView(WdRetrieveUpdateAPIView):
    model = Task
    serializer_class = TaskResultSerializer
    POST_DATA_RESPONSE = True

    def post_check_parameter(self, kwargs):
        code = super(TaskResultRetrieveAndUpdateView, self).post_check_parameter(kwargs)
        if code != ErrorCode.SUCCESS:
            return code
        self.request.data.update({"estate_confirm": None, "property_comfirm_time": None, "signature": None,
                                  "task_end_time": datetime.datetime.now()})
        return code


class TaskPushBackView(WdAPIView):
    """ 管理员将工单打回"""
    def post(self, request, *args, **kwargs):
        person_id = self.request.data.get("person_id", None)
        task_ids = self.request.data.get("tasks", None)
        if not person_id:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT, u'person_id为必传参数')
        if not task_ids:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT, u'tasks为必传参数')
        tasks = Task.objects.filter_active(id__in=task_ids)
        if not tasks:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT, u"工单不存在")
        tasks.update(transfer_to_id=person_id, status=100)
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS)


class TaskExportView(AuthenticationExceptView, WdAPIView):
    """ 生成html """
    def get(self, request, *args, **kwargs):
        task = self.request.GET.get("task", None)
        task = Task.objects.get(id=int(task))
        result = task.result
        if not result:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT, u"工单尚未完成 请完成后重试")
        result = json.loads(result)
        for dic in result['extra']:
            dic['image'] = dic['image'].strip(DOMAIN_NAME + "/uploaded/")
        context = {
            "register_code": task.elevator.register_code,
            "elevator_type": task.elevator.get_elevator_type_display(),
            "maintain_type": task.get_maintain_type_display(),
            "day": task.task_end_time.strftime("%Y-%m-%d %H:%M:%S"),
            "desc": result['maintenance_report'],
            "maintain_company_name": task.elevator.maintain_company.name,
            "property_company_name": task.elevator.property_company.name,
            "wb_content": result["selects"],
            "pictures": result['extra'],
            "maintain_signature": task.maintain_signature.strip(DOMAIN_NAME + "/uploaded/") if task.maintain_signature else None,
            "signature": task.signature.strip(DOMAIN_NAME + "/uploaded/") if task.signature else None
        }
        # return render(request, "task.html", context=context)
        return render(request, "task.html", context=context)


class TaskExportViewLevel2(WdAPIView):

    """ 工单导出"""
    def get(self, request, *args, **kwargs):
        user = self.request.user
        task_id = self.request.GET.get("task", None)
        if not task_id:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT, u"未传工单编号")
        task = Task.objects.filter(id=int(task_id)).first()
        if user.role != 0 and user.company_person.company.id != task.service_id:
            return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT, u"您无权查看其他维保单位工单")
        from_url = "http://127.0.0.1:8000/api/v1/maintain/task/pdf/?task=" + task_id
        # from_url = DOMAIN_NAME + "/api/v1/maintain/task/pdf/?task=" + task_id
        file_name = task.sn + ".pdf"
        # options = {
        #     'margin-bottom': '25mm',
        #     'margin-top': '25mm',
        #     'margin-left': '20mm',
        #     'margin-right': '20mm',
        # }

        options = {
            'page-size': 'A4',
            'margin-top': '25mm',
            'margin-right': '0mm',
            'margin-bottom': '25mm',
            'margin-left': '0mm',
            # 'orientation':'Landscape',#横向
            'encoding': "UTF-8",
            'no-outline': None,
            'footer-right':'[page]'  # 设置页码
        }
        try:
            print "from_url", from_url
            pdfkit.from_url(from_url, "../pdf/" + file_name, options)
            # pdfkit.from_url(from_url, "../pdf/" + file_name)
            # pdfkit.from_url("http://127.0.0.1:8080/api/v1/maintain/task/pdf/?task=111749", "xxx.pdf")
        except Exception as e:
            print e
        u = DOMAIN_NAME + "/pdf/" + file_name
        return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, u)


post_save.connect(receiver=task_data_sync, sender=Task)



























